package com.dfd.store.service.impl;

import java.sql.Connection;
import java.util.List;

import com.dfd.store.dao.OrderDao;
import com.dfd.store.dao.impl.OrderDaoImpl;
import com.dfd.store.domain.Order;
import com.dfd.store.domain.OrderItem;
import com.dfd.store.domain.PageModel;
import com.dfd.store.domain.User;
import com.dfd.store.service.OrderService;
import com.dfd.store.utils.BeanFactory;
import com.dfd.store.utils.JDBCUtils;

public class OrderServiceImpl implements OrderService {
	private OrderDao orderDao = (OrderDao) BeanFactory.getName("OrderDao");

	@Override
	public void saveOrder(Order order) throws Exception {
		// 保存订单和订单下所有的订单项(同时成功,失败);
		Connection conn = null;
		try {
			conn = JDBCUtils.getConnection();
			// 开启事务
			conn.setAutoCommit(false);
			// 保存订单,必须保证是同一个链接所以讲conn带上
			orderDao.saveOrder(conn, order);
			// 保存订单项
			for (OrderItem item : order.getList()) {
				orderDao.saveOrderItem(conn, item);
			}
			// 提交
			conn.commit();

		} catch (Exception e) {
			// 回滚
			e.printStackTrace();
		}
	}

	@Override
	public PageModel findOrderByUser(User user, int num) throws Exception {
		// 创建PM对象,:目的计算并携带参数
		// select count(*) from orders where uid = ?
		int totalRecords = orderDao.getTotalRecords(user);
		// int currentPageNum, int pageSize, int totalRecords)
		PageModel pModel = new PageModel(num, 10, totalRecords);
		// 关联集合
		// select * from orders where uid =? limit ?,?
		// 得到当前页面中的商品信息
		List list = orderDao.findOrderByUser(user, pModel.getStartIndex(), pModel.getPageSize());
		// 将商品信息存放到pm中
		pModel.setList(list);
		// 关联url
		pModel.setUrl("OrderServlet?method=findMyOrderWithPage");
		return pModel;
	}

	@Override
	public Order findOrderByOid(String oid) throws Exception {
		return orderDao.findOrderByOid(oid);
	}

	@Override
	public void updataOrder(Order order) throws Exception {
		orderDao.updataOrder(order);
	}

	@Override
	public List<Order> findAll() throws Exception {
		List<Order> orders = orderDao.findAll();
		return orders;
	}

	@Override
	public List<Order> findByState(int state) throws Exception {
		List<Order> orders =  orderDao.findByState(state);
		return orders;
	}


}
